import { fileURLToPath, URL } from 'node:url'

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import vueJsx from '@vitejs/plugin-vue-jsx'
import vueDevTools from 'vite-plugin-vue-devtools'


import legacyPlugin from '@vitejs/plugin-legacy'
import fs from 'fs'
import path from 'path'

export default ()=>{
  const processGlobal=process;
  function myPlugin(){
    // eslint-disable-next-line @typescript-eslint/ban-ts-comment
    // @ts-expect-error
    function getDirectoryStructure(directory) {
      const files = fs.readdirSync(directory);
      return files.map(filename => {
        const fullPath = path.join(directory, filename);
        const isDirectory = fs.statSync(fullPath).isDirectory();
        let obj={
          filename: filename,
          filepath: fullPath.replace(processGlobal.cwd(),''),
          isDirectory: isDirectory
        }
        if(isDirectory){
          // eslint-disable-next-line @typescript-eslint/ban-ts-comment
          // @ts-expect-error
          obj.children= getDirectoryStructure(fullPath);
          // eslint-disable-next-line @typescript-eslint/ban-ts-comment
          // @ts-expect-error
          if(obj.children.length>0){
            // eslint-disable-next-line @typescript-eslint/ban-ts-comment
            // @ts-expect-error
            const itemIndex=obj.children.filter((item)=>{return (item.filepath||'').includes('index.vue')})[0]
            if(itemIndex){
              for(const key in itemIndex){
                if(!['filename','filepath','isDirectory'].includes(key)){
                  // eslint-disable-next-line @typescript-eslint/ban-ts-comment
                  // @ts-expect-error
                  obj[key]=itemIndex[key]
                }
              }
            }
          }
        }else{
          // 读取.vue文件
          const fileData= fs.readFileSync(fullPath, {encoding:'utf8'});
          const codeString=fileData.toString()
          if(codeString.includes("@file")&&codeString.includes("file@")){
            let fileInfo=codeString.substring(codeString.indexOf("@file")+5,codeString.indexOf("file@"))
            try {
              fileInfo=(new Function('return '+ fileInfo))()
              // eslint-disable-next-line @typescript-eslint/ban-ts-comment
              // @ts-expect-error
              obj={...obj,...fileInfo}
            }catch (e) {
              console.log("代码文件中的@file{值}file@解析失败",e)
            }
            // eslint-disable-next-line @typescript-eslint/ban-ts-comment
            // @ts-expect-error
            if(!obj.title){
              // eslint-disable-next-line @typescript-eslint/ban-ts-comment
              // @ts-expect-error
              obj.title=filename.replace(".vue","")
            }
          }
        }
        // eslint-disable-next-line @typescript-eslint/ban-ts-comment
        // @ts-expect-error
        if(obj.children){
          // eslint-disable-next-line @typescript-eslint/ban-ts-comment
          // @ts-expect-error
          obj.children.sort((itemA,itemB)=>{
            if(itemA.index!==undefined&&itemB.index!==undefined){
              return itemA.index-itemB.index
            }
          })
        }
        return obj;
      });
    }
    // eslint-disable-next-line @typescript-eslint/ban-ts-comment
    // @ts-expect-error
    let config=null
    return {
      name: 'my-plugin',
      // eslint-disable-next-line @typescript-eslint/ban-ts-comment
      // @ts-expect-error
      config(config,command){
        if(command.command==='serve'){
          return {}
        }else{
          return {define:{nodejs_appFiles:JSON.stringify(getDirectoryStructure(processGlobal.cwd()+'\\src'))}}
        }
      },
      // eslint-disable-next-line @typescript-eslint/ban-ts-comment
      // @ts-expect-error
      configResolved(resolvedConfig){
        config=resolvedConfig
      },
      // eslint-disable-next-line @typescript-eslint/ban-ts-comment
      // @ts-expect-error
      transformIndexHtml(html){
        // eslint-disable-next-line @typescript-eslint/ban-ts-comment
        // @ts-expect-error
        if (config.command === 'serve') {
          // dev: 由开发服务器调用的插件
          return html.replace('</head>','<script id="nodejs_appFiles">window.nodejs_appFiles='+JSON.stringify(getDirectoryStructure(processGlobal.cwd()+'\\src'))+';setTimeout(function (){document.getElementById("nodejs_appFiles").remove()},1000*1)</script> </head>')
        }
      },
    }
  }
  return defineConfig({
    base: './',//设置相对目录，打包通用
    plugins: [
      vue(),
      vueJsx(),
      vueDevTools(),
      // 浏览器兼容问题配置
      legacyPlugin({
        targets: ['defaults', 'not ie <= 8','> 1%','last 2 versions','Firefox > 20'],
        additionalLegacyPolyfills: ['regenerator-runtime/runtime'],
        renderLegacyChunks: true,
        polyfills: [
          'es.symbol',
          'es.promise',
          'es.promise.finally',
          'es/map',
          'es/set',
          'es.array.filter',
          'es.array.for-each',
          'es.array.flat-map',
          'es.object.define-properties',
          'es.object.define-property',
          'es.object.get-own-property-descriptor',
          'es.object.get-own-property-descriptors',
          'es.object.keys',
          'es.object.to-string',
          'web.dom-collections.for-each',
          'esnext.global-this',
          'esnext.string.match-all'
        ]
      }),
      myPlugin() //自定义插件
    ],
    resolve: {
      extensions: ['.vue', '.json', '.js'],
      alias: {
        '@': fileURLToPath(new URL('./src', import.meta.url))
      },
    },
    //服务设置
    server: {
      port: 8001,//开启端口
      host: '0.0.0.0',//监听所有地址
      open: true,//服务启动时自动打开默认游览器
      cors: true,//允许跨域
      //自定义服务代理
      proxy: {
        '/api': 'http://127.0.0.1:9528/api/',
        '/api2/': 'http://127.0.0.1:9528/api2',
      }
    },
    //打包设置
    build: {
      target: "es2015",
      outDir: 'dist',
      sourcemap: false,//代码编译后是否生成map源文件，用于代码调试分析跟踪
      minify: 'terser',
      terserOptions: {
        compress: {
          drop_console: true,//  生产环境时移除console
          drop_debugger: true,//  生产环境时移除debugger
        }
      }
    }
  })
}
